package io.github.iogogogo.api;

import com.google.common.collect.Maps;
import io.github.iogogogo.commons.pdf.PdfGenerator;
import io.github.iogogogo.commons.support.wrapper.ResponseWrapper;
import io.github.iogogogo.commons.util.DateTimeUtils;
import io.github.iogogogo.commons.util.IdHelper;
import io.github.iogogogo.web.WebBaseApi;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FileUtils;
import org.springframework.http.HttpStatus;
import org.springframework.util.Assert;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.thymeleaf.context.Context;

import java.io.File;
import java.io.IOException;
import java.util.Map;

/**
 * @author tao.zeng9@outlook.com
 * @since 2025/7/2 17:20
 */
@Slf4j
@RestController
@RequestMapping("/api/pdf")
@Tag(name = "PDF生成管理")
@AllArgsConstructor
public class PdfApi implements WebBaseApi {

    private final PdfGenerator pdfGenerator;

    @PostMapping("/generate")
    public ResponseWrapper<?> generatePdf() throws Exception {
        Context context = new Context();
        context.setVariable("applyForm", getData());
        byte[] bytes = pdfGenerator.generatePdf("apply-order", context);
        Assert.notNull(bytes, "PDF生成失败！");
        String fileName = String.join(".", IdHelper.uuid(), "pdf");
        String filePath = saveTmpPreviewFile(fileName, bytes);
        return ok(filePath, HttpStatus.OK.getReasonPhrase());
    }

    private String saveTmpPreviewFile(String fileName, byte[] bytes) throws IOException {
        String tmpDir = System.getProperty("java.io.tmpdir");
        log.info("tmpDir:{}", tmpDir);
        String tmpFile = String.join(File.separator, tmpDir, fileName);
        FileUtils.writeByteArrayToFile(new File(tmpFile), bytes);
        return tmpFile;
    }

    private Map<String, Object> getData() {
        Map<String, Object> params = Maps.newHashMap();
        params.put("applyOrderId", IdHelper.id());
        params.put("applyTime", DateTimeUtils.formatLocalDateTime(DateTimeUtils.nowDateTime(), "yyyy-MM-dd HH:mm:SS"));
        params.put("deptName", "核心事业部");
        params.put("contact", "张三");
        params.put("contactTel", "13266668888");
        params.put("requirement", "主要需求是啥");
        return params;
    }
}
